# coding: utf-8
from PySide6.QtCore import QObject
from PySide6.QtGui import QPixmap

from .base import RequestHandler, ResponseHandler, EventSignalBus, QueueThread
from .image_thread import ImageRequest, ImageResponse, ImageSignalBus, imageRequest, imageSignalBus, LoadImageThread
from .sql_thread import DatabaseThread, sqlRequest, sqlSignalBus
from .worker_thread import WorkerThread, WorkerQueueThread, workerRequest, workerSignalBus
from ..db import init_create_table, create_session
from ..signal_bus import signalBus


class TotalWorkerObject(QObject):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.databaseThread = DatabaseThread(self)
        self.imageThread = LoadImageThread(self)
        self.workerThread = WorkerQueueThread(self)
        self.__connectSignals()

    def __connectSignals(self):
        sqlSignalBus.resultSignal.connect(self.onResult)
        imageSignalBus.resultSignal.connect(self.onImageResult)
        workerSignalBus.resultSignal.connect(self.onResult)

        self.workerThread.failed.connect(self.onFailed)
        self.databaseThread.failed.connect(self.onFailed)

        init_create_table()
        self.databaseThread.setServer(create_session)

    def onFailed(self, message: str):
        print(f"Failed: {message}")
        signalBus.msgSignal.emit("error", message)

    def onResult(self, response: ResponseHandler):
        try:
            if response.slot:
                response.slot(response.result)
        except RuntimeError as e:
            pass

    def onImageResult(self, response: ImageResponse):
        if response.slot:
            response.slot(response)
        else:
            try:
                label = response.label
                image = response.image
                if hasattr(label, 'setImage'):
                    label.setImage(image)
                else:
                    label.setPixmap(QPixmap.fromImage(image))
            except Exception as e:
                pass
